package com.github.binarylei.curator.atomicinteger;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.atomic.AtomicValue;
import org.apache.curator.framework.recipes.atomic.DistributedAtomicInteger;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.retry.RetryNTimes;
import org.junit.Test;

/**
 * 分布式计数器
 * @author: leigang
 * @version: 2018-04-06
 */
public class ZkCuratorAtomicInteger {

    private static final String CONNECT_ADDR = "127.0.0.1:2181";
    private static final int SEESION_OUTTIME = 5 * 1000;

    @Test
    public void test() throws Exception {
        //1. 重试策略：初试时间为1s，重试10次
        ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(1000, 10);

        //2. 通过工厂创建连接
        CuratorFramework cf = CuratorFrameworkFactory.builder()
                .connectString(CONNECT_ADDR)
                .sessionTimeoutMs(SEESION_OUTTIME)
                .retryPolicy(retryPolicy)
                .build();

        //3. 开启连接
        cf.start();

        //4. 使用 DistributedAtomicInteger
        DistributedAtomicInteger atomicInteger = new DistributedAtomicInteger(cf, "/curator",
                new RetryNTimes(3, 1000));

        atomicInteger.forceSet(0);
        atomicInteger.increment();
        AtomicValue<Integer> value = atomicInteger.get();

        System.out.println(value.succeeded());
        System.out.println(value.postValue());  //最新值????????
        System.out.println(value.preValue());   //原始值????????
    }
}
